package com.chixing.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chixing.commons.ServerResponse;
import com.chixing.mapper.MycouponMapper;
import com.chixing.pojo.*;
import com.chixing.service.*;
import com.chixing.utils.TokenUtil;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static java.time.LocalTime.now;

@RestController
public class MyorderController {

    @Autowired
    private ICouponService couponService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IMyorderDetailService myorderDetailService;

    @Autowired
    private IMyorderService myorderService;

    @Autowired
    private IMycouponService iMycouponService;

    @Autowired
    private MycouponMapper mycouponMapper;

    @Autowired
    private IAddressService addressService;


    @PostMapping("createMyorder")
    public ModelAndView createMyorder(String addressChosed,Integer couponChosed,Integer couponId,HttpSession session){
        SpikeProduct spikeProduct = (SpikeProduct) session.getAttribute("product");
        Users user = (Users) session.getAttribute("user");
        //System.out.println(couponChosed);
        Integer price = 0;
        if(couponChosed!=null)
            price = couponChosed;
        //System.out.println(couponId);
        Coupon coupon = couponService.getById(couponId);
        List<Address> addressList = (List<Address>)session.getAttribute("addressList");
        Integer addressId = null;
        for(int i=0; i<addressList.size();i++){
            if(addressChosed.contains(addressList.get(i).getAddressDetail()))
                addressId = addressList.get(i).getAddressId();
        }
        //创建订单
        Myorder myorder = new Myorder();
        myorder.setAddressId(addressId);
        myorder.setCouponId(couponId);
        myorder.setUserId(user.getUserId());
        myorder.setMyorderNumber(UUID.randomUUID().toString().replace("-",""));
        myorder.setCouponPrice(Float.valueOf(coupon.getCouponPrice()));
        myorder.setMyorderPrice(spikeProduct.getSpikeProductPrice()-price);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String createTime = sdf.format(date);
        myorder.setMyorderCreateTime(createTime);
        myorder.setMyorderStatus(0);
        myorderService.saveMyOrder(myorder);
        //创建订单详情
        MyorderDetail myorderDetail = new MyorderDetail();
        myorderDetail.setMyorderId(myorder.getMyorderId());
        myorderDetail.setMyorderDetailProductNums(1);
        myorderDetail.setProductId(spikeProduct.getProductId());
        myorderDetail.setMyorderDetailStatus(1);
        myorderDetail.setm1("xiaotao123");
        myorderDetail.setm2("xiaotao456");
        myorderDetailService.saveMyorderDetail(myorderDetail);
        //页面分发
        ModelAndView mav = new ModelAndView();
        mav.addObject("addressDetail",addressChosed);
        mav.addObject("order",myorder);
        mav.setViewName("pay_order/goPay.jsp");
        //延时队列，过期将订单状态改为已取消
        rabbitTemplate.convertAndSend("delayExchange","orderDelayCancel",myorder,message -> {
            message.getMessageProperties().setDelay(1000*60*15);
            return message;
        });
        //延时队列，订单即将过期提醒
        rabbitTemplate.convertAndSend("delayExchange","orderDelayTip",myorder,message -> {
            message.getMessageProperties().setDelay(1000*60*10);
            return message;
        });
        return mav;
    }

    @RabbitHandler
    @RabbitListener(queues = "payOrderQueue")
    public void changeOrderStatus(Myorder myorder, Message message , Channel channel){
        //System.out.println("消息被修改订单拿走了"+now());
        try {
            if(myorder.getMyorderStatus()==0)
                myorder.setMyorderStatus(1);
            myorderService.updateMyorder(myorder);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    @RabbitHandler
    @RabbitListener(queues = "newUpdateCouponQueue")
    public void changeMyCouponStatus(Myorder myorder,Message message,Channel channel){
        Integer couponId = myorder.getCouponId();
        Integer userId = myorder.getUserId();
        QueryWrapper<Mycoupon> wrapper = new QueryWrapper<>();
        wrapper.eq("coupon_id",couponId);
        wrapper.eq("user_id",userId);
        Mycoupon mycoupon = mycouponMapper.selectOne(wrapper);
        Integer update = iMycouponService.update(mycoupon);
        if(update>0){
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /* 我的订单页 */
    //订单页数据获取
    @GetMapping("getAllOrders")
    public ModelAndView getAllOrders(String token){
//        //1.从头部获得 token
//        String token = request.getHeader("token");
        System.out.println("token：" + token);

        //2.解析 token，获得登录用户的信息
        Integer userId = TokenUtil.parseToken(token).getCustId();
        System.out.println("userId：" + userId);

        //3.数据获取
        ServerResponse result = myorderService.getAll(userId);

        //4.数据绑定、页面分发
        ModelAndView mav = new ModelAndView();
        if(result.getResultcode() == 200){
            mav.addObject("result",result.getData()); //list<Map<String,Object>>
            mav.setViewName("/personal/myOrder.jsp");
        }
        return mav;
    }

    //订单页操作后状态修改
    @PostMapping("updateStatus")
    public int updateStatus(String orderNum){
        return myorderService.updateOrderStatus(orderNum);
    }

    //点击“立即付款”，到支付页面，拿 orderNum，orderPrice
    @GetMapping("zhifu/{orderNum}/{orderPrice}/{addressId}")
    public ModelAndView zhifu(@PathVariable("orderNum") String orderNum, @PathVariable("orderPrice") Float orderPrice, @PathVariable("addressId") Integer addressId){
        System.out.println("订单编号：" + orderNum);
        System.out.println("订单价格：" + orderPrice);
        System.out.println("地址id：" + addressId);

        Address address = addressService.getById(addressId);
        String detail = address.getAddressProvince() + address.getAddressCity() + address.getAddressArea() + address.getAddressDetail();
        
        Myorder myorder = new Myorder();
        myorder.setMyorderNumber(orderNum);
        myorder.setMyorderPrice(orderPrice);

        //没用
        myorder.setMyorderStatus(0);
        myorder.setMyorderCreateTime("111");
        myorder.setUserId(1);
        myorder.setAddressId(0);
        myorder.setCouponPrice(0f);
        myorder.setm1("z");
        myorder.setm2("z");
        System.out.println("myorder" + myorder);

        ModelAndView mav = new ModelAndView();
        mav.addObject("order",myorder);
        mav.addObject("addressDetail",detail);
        mav.setViewName("/pay_order/goPay.jsp");
        return mav;
    }

    @GetMapping("tofabiao/{orderId}")
    public ModelAndView tofabiao(@PathVariable("orderId") Integer orderId){
        Myorder myorder = myorderService.selectById(orderId);
        System.out.println("myorder：" + myorder);
        List<MyorderDetail> myorderDetail = myorderDetailService.getByMyorderId(orderId);
        System.out.println("myorderDetail：" + myorderDetail);

        ModelAndView mav = new ModelAndView();
        mav.addObject("result",myorder);
        mav.addObject("proid",myorderDetail.get(0).getProductId());
        mav.setViewName("/personal/fabiao.jsp");
        return mav;
    }

}
